package com.wrupple.muba.catalogs.client.module.services.stateful.impl;

import java.util.Collection;
import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.wrupple.muba.catalogs.client.activity.process.CatalogImportActivityProcess.ImportData;
import com.wrupple.muba.catalogs.client.activity.process.state.SimpleImportDataHandler;
import com.wrupple.muba.catalogs.client.module.services.logic.CatalogDescriptionService;
import com.wrupple.muba.catalogs.domain.CatalogEntry;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.vegetate.domain.CatalogDescriptor;

public abstract class ComplexImportDataHandler extends SimpleImportDataHandler {

	class SetCatalogDescriptor extends DataCallback<CatalogDescriptor> {
		ImportData parameter;
		StateTransition<List<CatalogEntry>> onDone; EventBus bus;
		
		public SetCatalogDescriptor(ImportData parameter,
				StateTransition<List<CatalogEntry>> onDone, EventBus bus) {
			super();
			this.parameter = parameter;
			this.onDone = onDone;
			this.bus = bus;
		}

		@Override
		public void execute() {
			baseCatalog = result;
			startSimpleImport(parameter, onDone, bus);
		}

	}

	private CatalogDescriptionService descriptor;
	protected CatalogDescriptor baseCatalog;
	private String baseCatalogid;
	
	public ComplexImportDataHandler(CatalogDescriptionService descriptor) {
		super();
		this.descriptor = descriptor;
	}

	@Override
	public void start(ImportData parameter,
			StateTransition<List<CatalogEntry>> onDone, EventBus bus) {
		baseCatalogid=parameter.catalog;
		DataCallback<CatalogDescriptor> setCatalogDescriptor = new SetCatalogDescriptor(parameter, onDone, bus);
		descriptor.loadCatalogDescriptor(baseCatalogid, setCatalogDescriptor);
	}
	
	private void startSimpleImport(ImportData parameter,
			StateTransition<List<CatalogEntry>> onDone, EventBus bus) {
		super.start(parameter, onDone, bus);
	}

	protected abstract StateTransition<JavaScriptObject> generateObjectImportTrigger(
			JavaScriptObject imported);

	protected JavaScriptObject generateMainCatalogObjectToPersist(
			JavaScriptObject imported) {
		assert baseCatalog != null : "Import Handler Has not been initialized";
		JSONObject origin = new JSONObject(imported);
		JSONObject regreso = new JSONObject();
		Collection<String> fieldNames = baseCatalog.getFieldNames();
		JSONValue originalFieldValue;
		for (String field : fieldNames) {
			originalFieldValue=origin.get(field);
			if(originalFieldValue==null||originalFieldValue.isNull()!=null){
				
			}else{
				regreso.put(field, originalFieldValue);
			}
		}

		return regreso.getJavaScriptObject();
	}

}
